package com.zhsj.OkeHomeConsumption.ui.fragment.minehome;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.hjq.base.BaseDialog;
import com.hjq.dialog.MenuDialog;
import com.hjq.permissions.OnPermission;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.hjq.widget.SettingBar;
import com.orhanobut.hawk.Hawk;
import com.zhsj.OkeHomeConsumption.R;
import com.zhsj.OkeHomeConsumption.common.Constants;
import com.zhsj.OkeHomeConsumption.common.MyLazyFragment;
import com.zhsj.OkeHomeConsumption.common.OkeHomeConsumptionApi;
import com.zhsj.OkeHomeConsumption.empty.FormalUserInfo;
import com.zhsj.OkeHomeConsumption.event.LoginOutEvent;
import com.zhsj.OkeHomeConsumption.event.LoginUserpanterEvent;
import com.zhsj.OkeHomeConsumption.network.HttpClient;
import com.zhsj.OkeHomeConsumption.network.JsonResponseHandler;
import com.zhsj.OkeHomeConsumption.other.TimeChecker;
import com.zhsj.OkeHomeConsumption.other.URLEntity;
import com.zhsj.OkeHomeConsumption.ui.activity.HomeActivity;
import com.zhsj.OkeHomeConsumption.ui.activity.LoginActivity;
import com.zhsj.OkeHomeConsumption.ui.activity.SettingActivity;
import com.zhsj.OkeHomeConsumption.ui.activity.UserBlancleActivity;
import com.zhsj.OkeHomeConsumption.ui.activity.WebActivity;
import com.zhsj.OkeHomeConsumption.ui.activity.bussiness.BusinessWalletActivity;
import com.zhsj.OkeHomeConsumption.ui.activity.wallet.CityWalletActivity;
import com.zhsj.OkeHomeConsumption.ui.activity.wallet.ProgressDrawableAlertDialog;
import com.zhsj.OkeHomeConsumption.ui.activity.wallet.TimeOutHandler;
import com.zhsj.OkeHomeConsumption.ui.activity.wallet.WalletActivity;
import com.zhsj.OkeHomeConsumption.ui.activity.wallet.packerview.ActionSheet;
import com.zhsj.OkeHomeConsumption.ui.fragment.entering.EnterActivity;
import com.zhsj.OkeHomeConsumption.utils.JsonUtils;
import com.zhsj.OkeHomeConsumption.utils.LogUtils;
import com.zhsj.OkeHomeConsumption.utils.PermissionFail;
import com.zhsj.OkeHomeConsumption.utils.PermissionSuccess;
import com.zhsj.OkeHomeConsumption.utils.PermissionUtil;
import com.zhsj.OkeHomeConsumption.utils.SharedPreferanceUtils;
import com.zhsj.OkeHomeConsumption.utils.SignUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import javax.xml.transform.Result;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import de.hdodenhof.circleimageview.CircleImageView;
import me.lxz.photopicker.camera.Mode;
import me.lxz.photopicker.camera.OnPhotoPickFinsh;
import me.lxz.photopicker.camera.PictureSelector;
import okhttp3.MediaType;

import static android.app.Activity.RESULT_OK;

/**
 * author : Xingdx
 * <p>
 * time   : 2018/10/18
 * desc   : 我的页面
 */
public final class MineHomeFragment extends MyLazyFragment<HomeActivity> implements ActionSheet.ActionSheetListener {

    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.phone)
    TextView phone;
    @BindView(R.id.sb_mine_data_cooperation)
    SettingBar sbMineDataCooperation;
    @BindView(R.id.message_linear)
    LinearLayout messageLinear;
    private SharedPreferanceUtils mSharePreferanceUtils = null;
    Unbinder unbinder;
    @BindView(R.id.avatar_img)
    CircleImageView avatarImg;
    @BindView(R.id.login_text)
    TextView loginText;
    @BindView(R.id.sb_mine_data_wallet)
    SettingBar sbMineDataWallet;
    @BindView(R.id.sb_mine_data_margin)
    SettingBar sbMineDataMargin;
    @BindView(R.id.sb_mine_data_order)
    SettingBar sbMineDataOrder;
    @BindView(R.id.sb_mine_data_invite)
    SettingBar sbMineDataInvite;
    @BindView(R.id.sb_mine_data_customer)
    SettingBar sbMineDataCustomer;
    @BindView(R.id.sb_mine_data_about_title)
    SettingBar sbMineDataAboutTitle;
    @BindView(R.id.tv_test_address)
    TextView tvTestAddress;
    @BindView(R.id.tv_test_right)
    TextView tv_test_right;

    //用户信息实体
    private FormalUserInfo userInfo = null;

    //拍照
    private int ViewId = -1;
    private final int PER_CAMERA = 3;

    //用户信息返回
    private static final int MESSAGE_RESULT = 5;
    /**
     * 实例化ProgressDrawableAlertDialog
     */
    private ProgressDrawableAlertDialog pDialogUtils = null;
    /**
     * 计时器
     */
    private TimeChecker timeChecker = null;

    public static MineHomeFragment newInstance() {
        return new MineHomeFragment();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_minehome;
    }

    @Override
    protected int getTitleId() {
        return R.id.tb_test_minehome_bar;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {
        mSharePreferanceUtils = new SharedPreferanceUtils(getActivity());
        pDialogUtils = new ProgressDrawableAlertDialog(getActivity());
        timeChecker = new TimeChecker(TimeOutHandler.timeOutHandler, Constants.TIME_OUT);
        userInfo = Hawk.get(Constants.SHARED_PERFERENCE_USERINFO);
        if (userInfo != null) {
            name.setVisibility(View.VISIBLE);
            if (!TextUtils.isEmpty(userInfo.getName())) {
                name.setText(userInfo.getName());
            } else {
                name.setText("");
            }
            phone.setVisibility(View.VISIBLE);
            if (!TextUtils.isEmpty(userInfo.getMobile())) {
                phone.setText(userInfo.getMobile());
            }
            if (!TextUtils.isEmpty(userInfo.getHeadImg())) {
                Glide.with(getActivity()).load(userInfo.getHeadImg()).into(avatarImg);
            }
        }
        if (mSharePreferanceUtils.getToken().equals("")) {
            loginText.setVisibility(View.VISIBLE);
            name.setVisibility(View.GONE);
            phone.setVisibility(View.GONE);

            loginText.setEnabled(true);
            sbMineDataMargin.setVisibility(View.GONE);
        } else {
            loginText.setVisibility(View.GONE);
            loginText.setEnabled(false);
            if (userInfo.getLifeUserDTO().getLifeType() != 0) {
                sbMineDataMargin.setVisibility(View.VISIBLE);
            }

        }

    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(FormalUserInfo formalUserInfo) {
        userInfo = formalUserInfo;
        Hawk.put(Constants.SHARED_PERFERENCE_USERINFO, userInfo);
        Constants.TOKEN = formalUserInfo.getToken();
        Glide.with(getActivity()).load(formalUserInfo.getHeadImg()).placeholder(R.drawable.zhanweitu_bg).into(avatarImg);
        mSharePreferanceUtils.setSaveUserInfo(formalUserInfo);
        mSharePreferanceUtils.setToken(formalUserInfo.getToken());
        mSharePreferanceUtils.setRongyunToken(formalUserInfo.getRongyunToken());
        mSharePreferanceUtils.setnumber(formalUserInfo.getLogin());
        name.setVisibility(View.VISIBLE);
        name.setText(formalUserInfo.getName());
        phone.setVisibility(View.VISIBLE);
        phone.setText(String.valueOf(userInfo.getMobile()));
        loginText.setVisibility(View.GONE);

        if (userInfo.getLifeUserDTO().getApplyCopartnerType() != 0 || userInfo.getLifeUserDTO().getLifeType() != 0) {
            sbMineDataMargin.setVisibility(View.VISIBLE);
        } else {
            sbMineDataMargin.setVisibility(View.GONE);
        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @OnClick({R.id.tv_test_address, R.id.tv_test_right, R.id.avatar_img, R.id.login_text, R.id.sb_mine_data_wallet, R.id.sb_mine_data_margin, R.id.sb_mine_data_order,
            R.id.sb_mine_data_invite, R.id.sb_mine_data_customer, R.id.sb_mine_data_about_title, R.id.sb_mine_data_cooperation, R.id.message_linear})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_test_address:
                //通知
                break;
            case R.id.tv_test_right:
                //设置
                startActivityForResult(new Intent(getActivity(), SettingActivity.class), 0);
                break;
            case R.id.avatar_img:
                //头像
                if (mSharePreferanceUtils.getToken().equals("")) {
                    startActivity(LoginActivity.class);
                } else {
                    // 头像点击
                    PermissionUtil.needPermission(this, PER_CAMERA, new String[]{Manifest.permission.CAMERA
                            , Manifest.permission.READ_EXTERNAL_STORAGE});
                }
                break;
            case R.id.message_linear:
                //个人信息
                if (mSharePreferanceUtils.getToken().equals("")) {
                    startActivity(LoginActivity.class);
                } else {
                    Intent intent = new Intent(getActivity(), MessageActivity.class);
                    startActivityForResult(intent, MESSAGE_RESULT);
                }
                break;
            case R.id.login_text:
                //登录
                startActivity(LoginActivity.class);
                break;
            case R.id.sb_mine_data_wallet:
                if (mSharePreferanceUtils.getToken().equals("")) {
                    startActivity(LoginActivity.class);
                } else {
                    switch (mSharePreferanceUtils.getlifeType()) {
                        case 0:
                            Intent intent = new Intent(getActivity(), WalletActivity.class);
                            startActivity(intent);
                            break;
                        case 1:
                            Intent intent5 = new Intent(getActivity(), BusinessWalletActivity.class);
                            startActivity(intent5);
                            break;
                        case 2:
                            Intent intent6 = new Intent(getActivity(), CityWalletActivity.class);
                            startActivity(intent6);
                            break;
                    }
                }


                //会员钱包
                break;
            case R.id.sb_mine_data_margin:
                //信誉保证金
                if (mSharePreferanceUtils.getToken().equals("")) {
                    startActivity(LoginActivity.class);
                } else {

                    switch (userInfo.getLifeUserDTO().getDepositStatusType()) {
                        case 3:
                            startActivityForResult(new Intent(getActivity(), ExtractBailActivity.class), 0);
                            break;
                        default:
                            if (userInfo.getLifeUserDTO().getApplyCopartnerType() == 0) {
                                startActivityForResult(new Intent(getActivity(), BailtwoActivity.class), 0);
                            } else {
                                startActivityForResult(new Intent(getActivity(), BailActivity.class), 0);
                            }
                            break;
                    }


                }
                break;
            case R.id.sb_mine_data_cooperation:
                //商务合作
                startActivityForResult(new Intent(getActivity(), EnterActivity.class), 0);
                break;
            case R.id.sb_mine_data_order:
                //交易订单
                startActivity(UserBlancleActivity.class);
                break;
            case R.id.sb_mine_data_invite:
                //我的团队
                startActivity(InviteActivity.class);
                break;
            case R.id.sb_mine_data_customer:
                //客服热线
                XXPermissions.with(getActivity())
                        .permission(Permission.CALL_PHONE) //不指定权限则自动获取清单中的危险权限
                        .request(new OnPermission() {

                            @Override
                            public void hasPermission(List<String> granted, boolean isAll) {
                                final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                                builder.setTitle("确定呼叫客服吗？");
                                builder.setMessage("号码:400-9931816");
                                builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {
                                        Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:400-9931816"));
                                        startActivity(intent);
                                    }
                                });
                                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {
                                        dialogInterface.dismiss();
                                    }
                                });
                                builder.show();
                            }

                            @Override
                            public void noPermission(List<String> denied, boolean quick) {
                            }
                        });

                break;
            case R.id.sb_mine_data_about_title:
                //关于我们
                Intent intent = new Intent(getActivity(), WebActivity.class).putExtra("url", OkeHomeConsumptionApi.ELVDOU_BASEURL_H5_LIFE + "app/h5/platform/2.html");
                startActivity(intent);
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case 0:
                //设置页面返回
                initData();
                break;
            case MESSAGE_RESULT:
                //用户信息页面返回
                if (resultCode == RESULT_OK) {
                    getUserMessage();
                }
                break;
        }
    }

    /**
     * 获取用户信息
     */
    public void getUserMessage() {
        // TODO Auto-generated method stub
        // post传参使用的HashMap
        HashMap<String, String> paramMaps = new HashMap<String, String>();
        // 生成sign值所使用的HashMap
        HashMap<String, String> mSendCodeHashMap = new HashMap<String, String>();
        // mParamHashMap.put("token", Constants.TOKEN);
        mSendCodeHashMap.put("v", Constants.APPVERSION);
        mSendCodeHashMap.put("t", Constants.TIME);
        mSendCodeHashMap.put("deviceId", URLEntity.getInstance().getImei());
        mSendCodeHashMap.put("platform", Constants.PLAFORM);
        mSendCodeHashMap.put("client", Constants.CLIENT);
        // 网络计时器及线程
        // 获取sign签名
        Constants.SIGN = SignUtil.getInstance().getSign(mSendCodeHashMap);
        HttpClient.get(OkeHomeConsumptionApi.ELVDOU_DETAIL, paramMaps, new JsonResponseHandler() {

            @Override
            public void onSuccess(int statusCode, String content) {
                // TODO Auto-generated method stub
                super.onSuccess(statusCode, content);
                LogUtils.e("个人信息", content.toString());
                try {
                    JSONTokener jsonT = new JSONTokener(content);
                    JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
                    String code = jsonOBJ.optString("code");
                    String message = jsonOBJ.optString("message");
                    if (code.equals("N000000")) {
                        JSONObject dataLoginobj = jsonOBJ.optJSONObject("data");
                        userInfo = JsonUtils.object(dataLoginobj.toString(), FormalUserInfo.class);
                        Hawk.put(Constants.SHARED_PERFERENCE_USERINFO, userInfo);
                        name.setVisibility(View.VISIBLE);
                        if (userInfo.getName() != null) {
                            name.setText(userInfo.getName());
                        } else {
                            name.setText("");
                        }
                        phone.setVisibility(View.VISIBLE);
                        phone.setText(String.valueOf(userInfo.getMobile()));
                        Glide.with(getActivity()).load(userInfo.getHeadImg()).into(avatarImg);
                        int member_flage = Hawk.get(Constants.MEMBER_FLAGE);
                        if (member_flage == -1) {
                            switch (userInfo.getLifeUserDTO().getDepositStatusType()) {
                                case 4:
                                    EventBus.getDefault().post(new LoginUserpanterEvent(0));
                                    break;
                                case 3:
                                    EventBus.getDefault().post(new LoginUserpanterEvent(0));
                                    break;
                            }
                        } else {
                            EventBus.getDefault().post(new LoginOutEvent(0));
                        }

                    } else {
                        if (!message.equals("null")) {
                            log(message);
                        }
                    }
                } catch (JSONException ex) {
                }

            }

            @Override
            public void onFailure(Throwable e) {
                super.onFailure(e);
            }
        });

    }

    @PermissionSuccess(requestCode = PER_CAMERA)
    private void grantPermissionSuccess() {
        getActivity().setTheme(R.style.ActionSheetStyleiOS7);
        ShootingDialog();
        ViewId = avatarImg.getId();
    }

    @PermissionFail(requestCode = PER_CAMERA)
    private void grantPersmissionFail() {
        toast("照相机权限被拒绝");
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        PermissionUtil.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    public void showActionSheet(int viewid) {
        ActionSheet.createBuilder(getActivity(), getFragmentManager(), viewid)
                .setCancelButtonTitle("取消")
                .setOtherButtonTitles("去拍照", "去图库")
                .setCancelableOnTouchOutside(true).setListener(this).show();
    }

    private void ShootingDialog() {
        String[] arreaArr = getActivity().getResources().getStringArray(R.array.shooting_type);
        final List<String> shooting_type_list = Arrays.asList(arreaArr);
        new MenuDialog.Builder(getActivity())
                .setCancel("取消") // 设置 null 表示不显示取消按钮
                //.setAutoDismiss(false) // 设置点击按钮后不关闭对话框
                .setList(shooting_type_list)
                .setListener(new MenuDialog.OnListener() {

                    @Override
                    public void onSelected(Dialog dialog, int position, String text) {
                        switch (position) {
                            case 0:
                                // 去拍照
                                PictureSelector
                                        .create(getActivity(), Mode.SYSTEM_CAMERA)
                                        .setListen(listen)
                                        .start();
                                break;
                            case 1:
                                // 图库选择
                                PictureSelector
                                        .create(getActivity(), Mode.AS_WEIXIN_IMGCAPTRUE)
                                        .setListen(listen)
                                        .start();
                                break;
                        }
                    }

                    @Override
                    public void onCancel(Dialog dialog) {
                        toast("取消了");
                    }
                })
                .setGravity(Gravity.BOTTOM)
                .setAnimStyle(BaseDialog.AnimStyle.BOTTOM)
                .show();
    }

    @Override
    public void onDismiss(ActionSheet actionSheet, boolean isCancel) {

    }

    @Override
    public void onOtherButtonClick(ActionSheet actionSheet, int index, int viewId) {
        switch (index + 1) {
            case 1:


                break;
            case 2:

                break;

            default:
                break;
        }
    }

    OnPhotoPickFinsh listen = new OnPhotoPickFinsh() {
        @Override
        public void onPhotoPick(List<File> list) {
            switch (ViewId) {
                case R.id.avatar_img:
                    ImgUPload(list.get(0), ViewId);
                    break;
            }
        }
    };

    /**
     * 上传图片异步请求方法
     *
     * @param
     * @return 创建时间：2017/1/17 17:16
     */
    public void ImgUPload(final File imgpathfile, final int ViewId) {
        // TODO Auto-generated method stub
        // 生成sign值所使用的HashMap
        final HashMap<String, String> mLogOnHashMap = new HashMap<String, String>();
        mLogOnHashMap.put("v", Constants.APPVERSION);
        mLogOnHashMap.put("t", Constants.TIME);
        LogUtils.e("ImgUPload time =", Constants.TIME);
        mLogOnHashMap.put("deviceId", URLEntity.getInstance().getImei());
        mLogOnHashMap.put("platform", Constants.PLAFORM);
        mLogOnHashMap.put("deviceToken", Constants.DEVICETOKEN);
        mLogOnHashMap.put("client", Constants.CLIENT);
        // 网络计时器及线程
        TimeOutHandler.pDialogUtils = pDialogUtils;
        pDialogUtils.show();
        timeChecker.start();
        // 获取sign签名
        Constants.SIGN = SignUtil.getInstance().getSign(mLogOnHashMap);
        LogUtils.e("上传头像参数", mLogOnHashMap.toString());
        LogUtils.e("上传头像", OkeHomeConsumptionApi.ELVDOU_USER_HEADER);
        HttpClient.uploadFile(OkeHomeConsumptionApi.ELVDOU_USER_HEADER, imgpathfile, MediaType.parse("image/png"), new JsonResponseHandler() {

            @Override
            public void onSuccess(int statusCode, String content) {
                // TODO Auto-generated method stub
                super.onSuccess(statusCode, content);
                timeChecker.check();
                pDialogUtils.dismiss();
                TimeOutHandler.pDialogUtils = null;
                LogUtils.e("上传头像", content.toString());
                try {
                    JSONTokener jsonT = new JSONTokener(content);
                    JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
                    String code = jsonOBJ.optString("code");
                    String message = jsonOBJ.optString("message");
                    String data = jsonOBJ.optString("data");
                    if (code.equals("N000000")) {
                        Glide.with(getActivity()).load(data).thumbnail(0.1f).into(avatarImg);
                    } else if (code.equals(Constants.STATUSTOKENERROR)) {
                        // token过期
                        if (!message.equals("null")) {
                            toast(message);
                        }
                    } else {
                        if (!message.equals("null")) {
                            toast(message);
                        }
                    }
                } catch (JSONException ex) {
                    LogUtils.e("RegisterActivity", "sendcode异常 ");
                }
            }

            @Override
            public void onFailure(Throwable e) {
                // TODO Auto-generated method stub
                super.onFailure(e);
                timeChecker.check();
                pDialogUtils.dismiss();
                TimeOutHandler.pDialogUtils = null;
                LogUtils.e("onFailure", "" + e.toString());
            }
        });
    }
}